package com.jee.ssm.modules.parkDepot.app;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.jee.ssm.common.config.AiparkConfig;
import com.jee.ssm.common.utils.*;
import com.jee.ssm.common.utils.hik.HikUtils;
import com.jee.ssm.model.ParkDepot;
import com.jee.ssm.model.PersonalMessage;
import com.jee.ssm.model.ReservationRecord;
import com.jee.ssm.model.User;
import com.jee.ssm.model.aipark.AiparkReceive;
import com.jee.ssm.model.hik.HikPage;
import com.jee.ssm.model.hik.receive.ParkDepotInfo;
import com.jee.ssm.model.hik.receive.ReservationReturn;
import com.jee.ssm.model.hik.receive.VehicleRecord;
import com.jee.ssm.model.json.Tip;
import com.jee.ssm.modules.parkDepot.services.ParkDepotService;
import com.jee.ssm.modules.personalMessage.services.PersonalMessageService;
import com.jee.ssm.modules.reservationRecord.services.ReservationRecordService;
import com.jee.ssm.modules.user.services.UserService;
import org.apache.commons.httpclient.NameValuePair;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.ParseException;
import java.util.*;

/**
 * 停车场管理 客户端 Controller
 *
 * @author GaoXiang
 * @version 1.0
 */
@Controller
@RequestMapping("/app/parkDepot")
public class AppParkDepotController {

    /**
     * 查询停车场列表
     * @param timestamp
     * @param token
     * @return
     */
//	@RequestMapping(value = "/parkDepotList", method = RequestMethod.GET)
//	@ResponseBody
//	public Tip parkDepotList(long timestamp, String token) {
//		Tip tip = TokenUtils.verifyToken(timestamp, token);
//		if(tip.getSuccess()) {
//			tip = HikUtils.getParkingInfos(1, 400);
//			if(tip.getSuccess()) {
//				List<ParkDepotInfo> array = new ArrayList<>();
//				List<ParkDepotInfo> list = JSON.parseArray(JSONArray.toJSONString(tip.getData()), ParkDepotInfo.class);
//	            for(ParkDepotInfo p : list) {
//	                ParkDepot parkDepot = parkDepotService.findByHikId(p.getParkCode());
//	                if(parkDepot != null) {
//	                    p.setParkDepot(parkDepot);
//	                    array.add(p);
//	                }
//	            }
//	            tip = new Tip(array);
//			} else {
//				tip = new Tip(2, "未查找到停车场");
//			}
//		}
//		return tip;
//	}

    /**
     * 查询停车场列表
     *
     * @param timestamp
     * @param token
     * @return
     */
    @RequestMapping(value = "/parkingList", method = RequestMethod.GET)
    @ResponseBody
    public Tip parkingList(long timestamp, String token) {
        Tip tip = TokenUtils.verifyToken(timestamp, token);
        if (tip.getSuccess()) {
            tip = HikUtils.getParkingInfos(1, 400);
            if (tip.getSuccess()) {
                List<ParkDepotInfo> array = new ArrayList<>();
                List<ParkDepotInfo> list = JSON.parseArray(JSONArray.toJSONString(tip.getData()), ParkDepotInfo.class);
                for (ParkDepotInfo p : list) {
                    ParkDepot parkDepot = parkDepotService.findByHikId(p.getParkCode());
                    if (parkDepot != null) {
                        p.setParkDepot(parkDepot);
                        array.add(p);
                    }
                }
                tip = new Tip(array);
            } else {
                tip = new Tip(2, "未查找到停车场");
            }
        }
        return tip;
    }

    /**
     * 附近停车场
     *
     * @param lat           纬度
     * @param lng           经度
     * @param searchContent 检索内容
     * @return
     */
    @RequestMapping(value = "/nearByParkDepot", method = RequestMethod.GET)
    @ResponseBody
    public Tip nearByParkDepot(long timestamp, String token, double lat, double lng, String searchContent) {
        Tip tip = TokenUtils.verifyToken(timestamp, token);
        if (tip.getSuccess()) {
            List<ParkDepot> list = parkDepotService.nearByParkDepot(CalculateUtils.findNeighPosition(lat, lng, new ParkDepot(searchContent)));
            for (ParkDepot pd : list) {
                pd = HikUtils.handleParkDepot(pd);
            }
            tip.setData(list);
        }
        return tip;
    }

    /**
     * 只通过名称关键字检索附近停车场
     *
     * @param searchContent 检索内容
     * @return
     */
    @RequestMapping(value = "/searchNearByParkDepot", method = RequestMethod.GET)
    @ResponseBody
    public Tip searchNearByParkDepot(long timestamp, String token, String searchContent) {
        Tip tip = TokenUtils.verifyToken(timestamp, token);
        if (tip.getSuccess()) {
            List<ParkDepot> list = parkDepotService.searchNearByParkDepot(new ParkDepot(searchContent));
            for (ParkDepot pd : list) {
                pd = HikUtils.handleParkDepot(pd);
            }
            tip.setData(list);
        }
        return tip;
    }

    /**
     * 根据id获取停车场
     *
     * @param id 停车场标识
     * @return 停车场详情
     */
    @RequestMapping(value = "/findParkDepotById", method = RequestMethod.GET)
    @ResponseBody
    public Tip findParkDepotById(long timestamp, String token, String id) {
        Tip tip = TokenUtils.verifyToken(timestamp, token);
        if (tip.getSuccess()) {
            ParkDepot pd = parkDepotService.selectById(id);
            tip = new Tip(HikUtils.handleParkDepot(pd));
        }
        return tip;
    }

    /**
     * 停车场编号查询停车场详情
     * 根据
     *
     * @param timestamp
     * @param token
     * @param id
     * @return
     */
    @RequestMapping(value = "/getParkingInfoByParkCode", method = RequestMethod.GET)
    @ResponseBody
    public Tip getParkingInfoByParkCode(long timestamp, String token, String id) {
        Tip tip = TokenUtils.verifyToken(timestamp, token);
        if (tip.getSuccess()) {
            tip = HikUtils.getParkingInfoByParkCode(id);
            if (tip.getSuccess()) {
                if (tip.getData() != null) {
                    ParkDepotInfo p = JSONObject.parseObject(JSONArray.toJSONString(tip.getData()), ParkDepotInfo.class);
                    if (p != null) {
                        ParkDepot parkDepot = parkDepotService.findByHikId(p.getParkCode());
                        p.setParkDepot(parkDepot);
                        tip = new Tip(p);
                    }
                }
            }
        }
        return tip;
    }

    /**
     * 计算预约费用
     *
     * @param payTime  预约开始时间
     * @param parkTime 入场时间
     * @param parkCode 停车场编号
     * @return 预约费用
     */
    @RequestMapping(value = "/calculateOrderFee", method = RequestMethod.GET)
    @ResponseBody
    public Tip calculateOrderFee(long timestamp, String token, String payTime, String parkTime, String parkCode) {
        Tip tip = TokenUtils.verifyToken(timestamp, token);
        if (tip.getSuccess()) {
            tip = cal(payTime, parkTime, parkCode);
        }
        return tip;
    }

    public Tip cal(String payTime, String parkTime, String parkCode) {
        Tip tip = new Tip(1, "请选择正确的时间");
        try {
            Date payDate = new Date();
            Date parkDate = TimeUtils.getDateByString(parkTime);
            long ms = parkDate.getTime() - payDate.getTime();
            if (ms > 0) {
                int hour = TimeUtils.getHours(ms), minute = TimeUtils.getMinutes(ms);
                ParkDepot parkDepot = parkDepotService.findByHikId(parkCode);
                if (parkDepot != null) {
                    BigDecimal money = CalculateUtils.multiply(parkDepot.getOrderFee(), hour);
                    ReservationRecord r = new ReservationRecord(parkDepot.getOrderFee(), minute, String.valueOf(money), payDate, parkDate);
                    tip = new Tip(r);
                } else {
                    tip = new Tip(4, "停车场查询错误，请退出重试");
                }
            } else {
                tip = new Tip(3, "最晚入场时间必须大于预约开始时间");
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return tip;
    }

    /**
     * 预约车位
     *
     * @param userId     用户标识
     * @param parkName   停车场名称
     * @param parkCode   停车场编号
     * @param plateNo    车牌号码
     * @param plateColor 车牌颜色
     * @param payTime    预订开始时间
     * @param parkTime   预约进场时间
     * @param telephone  联系人电话
     * @param plotNum    车位号
     * @return
     */
    @RequestMapping(value = "/parkReservation", method = RequestMethod.POST)
    @ResponseBody
    public Tip parkReservation(long timestamp, String token, String userId, String parkName, String parkCode, String plateNo, Integer plateColor, String payTime, String parkTime, String telephone, String plotNum) {
        Tip tip = TokenUtils.verifyToken(timestamp, token);
        if (tip.getSuccess()) {
            User user = userService.selectById(userId);
            if (user != null) {
                tip = cal(payTime, parkTime, parkCode);
                if (tip.getSuccess()) {
                    ReservationRecord r = JSONObject.parseObject(JSONArray.toJSONString(tip.getData()), ReservationRecord.class);
                    BigDecimal f = new BigDecimal(r.getBookFee());
                    if (user.getWalletBalance().compareTo(f) != -1) {
                        tip = HikUtils.parkReservation(parkCode, plateNo, plateColor, payTime, r.getBookDuration(), telephone, plotNum);
                        if (tip.getSuccess()) {
                            try {
                                ReservationReturn rrn = JSON.toJavaObject(JSONObject.parseObject(tip.getData().toString()), ReservationReturn.class);
                                System.out.println(rrn.toString());
                                user.setWalletBalance(CalculateUtils.subtract(user.getWalletBalance(), f));
                                ReservationRecord rr = new ReservationRecord(UUIDFactory.getStringId(), rrn.getBillNo(), new Date(), userId, user.getPhone(), user.getUserName(), user.getName(), user.getIdNumber(), r.getOrderFee(), r.getBookDuration(), r.getBookFee(), parkName, parkCode, plateNo, plateColor, r.getPayTime(), r.getParkTime(), telephone, rrn.getPlotNo(), 1, null);
                                reservationRecordService.insert(rr);
                                userService.updateWalletBalanceById(user, "-", f, "预定" + parkName + "的车位", 1, 2, null, "", "0",new Date(),new Date(),0,plateNo);
                                PersonalMessage pm = new PersonalMessage(UUIDFactory.getStringId(), "预约成功", user.getId(), user.getPhone(), user.getUserName(), user.getName(), user.getIdNumber(), 0, 0, new Date(), new Date(), "您在" + TimeUtils.getStringDayTime(new Date()) + "提交的预约申请已成功，车牌号：" + plateNo + "，扣除余额" + String.valueOf(f) + "元，请准时到达" + parkName + "停车场。");
                                try {
                                    personalMesssageService.insert(pm);
                                } catch (Exception e) {
                                    System.out.println("消息保存失败 ");
                                }
                                try {
                                    PushUtils.pushPersonalMessageToOne(pm);
                                    PushUtils.pushPersonalMessageToOneIos(pm);
                                }catch (Exception e){
                                    PushUtils.pushPersonalMessageToOneIos(pm);
                                }finally {
                                    return tip;
                                }

                            } catch (Exception e) {
                                e.printStackTrace();
                                System.out.println("订单生成，但是扣除押金失败");
                            }
                        }
                    } else {
                        tip = new Tip(1, "余额不足，请及时充值");
                    }

                }
            } else {
                tip = new Tip(2, "用户信息失效，请重新登录");
            }
        }
        return tip;
    }

    /**
     * 查询半小时前的过车数据
     *
     * @return
     */
//	@RequestMapping(value = "/vehicleRecords", method = RequestMethod.GET)
//	@ResponseBody
//	public Tip vehicleRecords() {
//		Tip tip = HikUtils.getVehicleRecords(1, 400, "", "", "", System.currentTimeMillis() - 600000, System.currentTimeMillis() - 300000, null, null);
//		List<VehicleRecord> newVehicleRecordList = new ArrayList<>();
//;		if(tip.getSuccess()) {
//			HikPage hp = JSONObject.parseObject(String.valueOf(tip.getData()), HikPage.class);
//			List<VehicleRecord> vehicleRecordList = JSON.parseArray(JSONArray.toJSONString(hp.getList()),VehicleRecord.class);
//			for (int i = 0 ; i < vehicleRecordList.size() ; i+=2) {
//				newVehicleRecordList.add(vehicleRecordList.get(i));
//			}
//			tip = new Tip(newVehicleRecordList);
//		}
//		return tip;
//	}
    @RequestMapping(value = "/sendParkDepot", method = RequestMethod.GET)
    @ResponseBody
    public Tip sendParkDepot(String id) {
        Tip tip = new Tip();
        tip = HikUtils.getParkingInfoByParkCode(id);
        if (tip.getSuccess() && tip.getData() != null) {
            ParkDepotInfo p = JSONObject.parseObject(JSONArray.toJSONString(tip.getData()), ParkDepotInfo.class);
            ParkDepot pd = parkDepotService.findByHikId(p.getParkCode());
            if (pd != null) {
                String num = UUIDFactory.get36Id();
                Map<String, String> map = new HashMap<>();
                map.put("accessKey", "57EF312FEDAD8CE5");
                map.put("parkCode", pd.getAiparkCode());
                map.put("parkName", p.getParkName());
                map.put("parkType", p.getParkType() == 1 ? "1" : "3");
                map.put("cityCode", "130304");
                map.put("address", "奥林匹克公园北");
                map.put("image", "http://117.132.167.10:23108/image/3/3/322bc1512226499780984b7d613d97aa/0/22/6895/206502034/31100");
                map.put("lng", p.getParkLongitude().toString());
                map.put("lat", p.getParkLatitude().toString());
                map.put("totalSpace", p.getTotalPlot().toString());
                map.put("isFree", "1");
                map.put("rsType", "0");
                map.put("tobType", "0");
                map.put("oprNum", num);
                map.put("tenantCode", "1003");
                String signature = SingUtils.sing(map, "U2FsdGVkX18uWXs4C3evsGHcQbGYuUFxchjQYkDJfkgb5UI45SSeC8d4evm6v0Rd");
                map.put("signature", signature);
//				String param = ParamFormatUtil.formatParameterMap(map, false, false);
//				String data = JSONObject.toJSONString(map);
                NameValuePair[] data = {
                        new NameValuePair("accessKey", map.get("accessKey")),
                        new NameValuePair("parkCode", map.get("parkCode")),
                        new NameValuePair("parkName", map.get("parkName")),
                        new NameValuePair("parkType", map.get("parkType")),
                        new NameValuePair("cityCode", map.get("cityCode")),
                        new NameValuePair("address", map.get("address")),
                        new NameValuePair("image", map.get("image")),
                        new NameValuePair("lng", map.get("lng")),
                        new NameValuePair("lat", map.get("lat")),
                        new NameValuePair("totalSpace", map.get("totalSpace")),
                        new NameValuePair("isFree", map.get("isFree")),
                        new NameValuePair("rsType", map.get("rsType")),
                        new NameValuePair("tobType", map.get("tobType")),
                        new NameValuePair("oprNum", map.get("oprNum")),
                        new NameValuePair("signature", map.get("signature")),
                        new NameValuePair("tenantCode", map.get("tenantCode"))
                };
                try {
                    String rs = HttpUtils.doPost("http://commonthrid.pre.gplus.qhd.aipark.com/third/qhd/park/syncPark", data);
                    System.out.println(rs);
                    tip.setData(rs);
                } catch (IOException e) {
                    e.printStackTrace();
                }
//				String rs = HttpUtil.doPost("http://commonthrid.pre.gplus.qhd.aipark.com/third/qhd/park/syncPark?accessKey=57EF312FEDAD8CE5", data);
//				System.out.println(rs);
//				tip.setData(rs);
            }
        }
        return tip;
    }

    @RequestMapping(value = "/sendRecord", method = RequestMethod.GET)
    @ResponseBody
    public Tip sendRecord() {

        long begin = System.currentTimeMillis();
        Integer a = 0, b = 0;
        Tip tip = HikUtils.getVehicleRecords(1, 400, "", "", "", System.currentTimeMillis() - 600000, System.currentTimeMillis(), null, 1);
        if (tip.getSuccess()) {
            HikPage hp = JSONObject.parseObject(String.valueOf(tip.getData()), HikPage.class);
            List<VehicleRecord> list = JSON.parseArray(JSONArray.toJSONString(hp.getList()), VehicleRecord.class);
            System.out.println("查询到出车记录：" + list.size() + "条");
            for (int i = 0; i < list.size(); i++) {
                ParkDepot pd = parkDepotService.findByHikId(list.get(i).getParkCode());
                if (pd != null && pd.getAiparkStatus() == 1) {
                    Tip t = HikUtils.getVehicleRecords(1, 400, pd.getHikId(), "", list.get(i).getPlateNo(), null, null, null, 0);
//					System.out.println("第" + i + "条出车查询到入场状态为：" + t.getSuccess());
                    if (t.getSuccess()) {
                        HikPage h = JSONObject.parseObject(String.valueOf(t.getData()), HikPage.class);
                        List<VehicleRecord> l = JSON.parseArray(JSONArray.toJSONString(h.getList()), VehicleRecord.class);
                        if (l.size() > 0) {
                            String n = UUIDFactory.get32Id();
                            AiparkReceive ar = sendSingleEntry(pd, l.get(0), n);
                            if ("0".equals(ar.getState())) {
                                a++;
                                AiparkReceive s = sendSingleExit(pd, list.get(i), l.get(0), n);
                                if ("0".equals(s.getState())) {
                                    b++;
                                }
                            } else if ("26".equals(ar.getState())) {
                                System.out.println("入场记录已经上传，返回的编号为：" + ar.getDesc());
                                AiparkReceive s = sendSingleExit(pd, list.get(i), l.get(0), ar.getDesc());
                                if ("0".equals(s.getState())) {
                                    b++;
                                } else {
                                    System.out.println("出场记录上传异常：" + s.toString());
                                }
                            } else {
                                System.out.println("入场记录上传异常：" + ar.toString());
                            }

                        }
                    }
                }
            }
        }
        long end = System.currentTimeMillis();

        long time = end - begin;

        System.out.println("查询耗时：" + TimeUtils.formatTime(time));
        System.out.println("入场记录上传成功" + a + "条");
        System.out.println("出场记录上传成功" + b + "条");

        return tip;
    }

    public AiparkReceive sendSingleEntry(ParkDepot pd, VehicleRecord v, String rn) {
        String url = "https://www.yhxiadu.com/app/parkDepot/checkParkPicture?unid=" + v.getUnid() + "&code=" + v.getParkCode();
        System.out.println(url);
        String num = UUIDFactory.get36Id();
        Map<String, String> map = new HashMap<>();
        map.put("accessKey", AiparkConfig.accessKey);
        map.put("plateNumber", v.getPlateNo());
        map.put("plateColor", String.valueOf(v.getPlateColor()));
        map.put("parkCode", pd.getAiparkCode());
        map.put("berthNumber", String.valueOf(v.getBerthCode()));
        map.put("carType", String.valueOf(v.getCarType()));
        map.put("entryTime", String.valueOf(TimeUtils.getDateByStringNoException(v.getPassTime()).getTime()));
        map.put("timestamp", String.valueOf(System.currentTimeMillis()));
        map.put("recordCode", rn);
        map.put("oprNum", num);
        map.put("entryPlatePic", url);
        map.put("entryFeaturePic", url);
        map.put("tenantCode", AiparkConfig.tenantCode);
        String signature = SingUtils.sing(map, AiparkConfig.accessSecret);
        map.put("signature", signature);
        NameValuePair[] data = {
                new NameValuePair("accessKey", map.get("accessKey")),
                new NameValuePair("plateNumber", map.get("plateNumber")),
                new NameValuePair("plateColor", map.get("plateColor")),
                new NameValuePair("parkCode", map.get("parkCode")),
                new NameValuePair("berthNumber", map.get("berthNumber")),
                new NameValuePair("carType", map.get("carType")),
                new NameValuePair("entryTime", map.get("entryTime")),
                new NameValuePair("timestamp", map.get("timestamp")),
                new NameValuePair("recordCode", map.get("recordCode")),
                new NameValuePair("oprNum", map.get("oprNum")),
                new NameValuePair("entryPlatePic", map.get("entryPlatePic")),
                new NameValuePair("entryFeaturePic", map.get("entryFeaturePic")),
                new NameValuePair("signature", map.get("signature")),
                new NameValuePair("tenantCode", map.get("tenantCode"))
        };
        AiparkReceive h = null;
        try {
            String rs = HttpUtils.doPost(AiparkConfig.syncEntryUrl, data);
            h = JSONObject.parseObject(rs, AiparkReceive.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return h;
    }

    public AiparkReceive sendSingleExit(ParkDepot pd, VehicleRecord v, VehicleRecord vr, String rn) {
        String url = "https://www.yhxiadu.com/app/parkDepot/checkParkPicture?unid=" + v.getUnid() + "&code=" + v.getParkCode();
        String num = UUIDFactory.get36Id();
        Map<String, String> map = new HashMap<>();
        map.put("accessKey", AiparkConfig.accessKey);
        map.put("plateNumber", v.getPlateNo());
        map.put("plateColor", String.valueOf(v.getPlateColor()));
        map.put("parkCode", pd.getAiparkCode());
        map.put("berthNumber", String.valueOf(v.getBerthCode()));
        map.put("carType", String.valueOf(v.getCarType()));

        map.put("entryTime", String.valueOf(TimeUtils.getDateByStringNoException(vr.getPassTime()).getTime()));
        map.put("exitTime", String.valueOf(TimeUtils.getDateByStringNoException(v.getPassTime()).getTime()));
        map.put("agioMoney", "0.00");
        map.put("shouldPay", "0.00");
        map.put("actualPay", "0.00");
        map.put("recordType", "0");
        map.put("timestamp", String.valueOf(System.currentTimeMillis()));
        map.put("recordCode", rn);
        map.put("oprNum", num);
        map.put("exitPlatePic", url);
        map.put("exitFeaturePic", url);
        map.put("tenantCode", AiparkConfig.tenantCode);
        String signature = SingUtils.sing(map, AiparkConfig.accessSecret);
        map.put("signature", signature);
        NameValuePair[] data = {
                new NameValuePair("accessKey", map.get("accessKey")),
                new NameValuePair("plateNumber", map.get("plateNumber")),
                new NameValuePair("plateColor", map.get("plateColor")),
                new NameValuePair("parkCode", map.get("parkCode")),
                new NameValuePair("berthNumber", map.get("berthNumber")),
                new NameValuePair("carType", map.get("carType")),
                new NameValuePair("entryTime", map.get("entryTime")),
                new NameValuePair("exitTime", map.get("exitTime")),
                new NameValuePair("agioMoney", map.get("agioMoney")),
                new NameValuePair("shouldPay", map.get("shouldPay")),
                new NameValuePair("actualPay", map.get("actualPay")),
                new NameValuePair("recordType", map.get("recordType")),
                new NameValuePair("timestamp", map.get("timestamp")),
                new NameValuePair("recordCode", map.get("recordCode")),
                new NameValuePair("oprNum", map.get("oprNum")),
                new NameValuePair("exitPlatePic", map.get("exitPlatePic")),
                new NameValuePair("exitFeaturePic", map.get("exitFeaturePic")),
                new NameValuePair("signature", map.get("signature")),
                new NameValuePair("tenantCode", map.get("tenantCode"))
        };
        AiparkReceive ar = null;
        try {
            String rs = HttpUtils.doPost(AiparkConfig.syncExitUrl, data);
            ar = JSONObject.parseObject(rs, AiparkReceive.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ar;
    }

    @RequestMapping(value = "/checkParkPicture", method = RequestMethod.GET)
    public void checkParkPicture(String unid, String code, HttpServletRequest request, HttpServletResponse response) {
        Tip tip = HikUtils.getPassPicByUuid(unid, code);
        if (tip.getSuccess()) {
            String netUrl = tip.getData().toString();
            getImageFromNet(request, response, netUrl);
        }
    }

    public void getImageFromNet(HttpServletRequest request, HttpServletResponse response, String netUrl) {
        try {
            String url = "/images/net/";
            String path = request.getServletContext().getRealPath(url);
            String fileName = System.currentTimeMillis() + UUIDFactory.get32Id() + ".jpg";
            File file = new File(path);
            if (!file.exists() && !file.isDirectory()) {
                file.mkdirs();
            }

            saveToFile(netUrl, path + fileName);
            outputStream(response, new FileInputStream(new File(path + fileName)));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void saveToFile(String destUrl, String path) {
        FileOutputStream fos = null;
        BufferedInputStream bis = null;
        HttpURLConnection httpUrl = null;
        URL url;
        int BUFFER_SIZE = 1024;
        byte[] buf = new byte[BUFFER_SIZE];
        int size = 0;
        try {
            url = new URL(destUrl);
            httpUrl = (HttpURLConnection) url.openConnection();
            httpUrl.connect();
            bis = new BufferedInputStream(httpUrl.getInputStream());
            fos = new FileOutputStream(path);
            while ((size = bis.read(buf)) != -1) {
                fos.write(buf, 0, size);
            }
            fos.flush();
        } catch (IOException | ClassCastException e) {
            e.printStackTrace();
        } finally {
            try {
                assert fos != null;
                fos.close();
                bis.close();
                httpUrl.disconnect();
            } catch (IOException | NullPointerException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 输出文件流
     *
     * @param response
     * @param in
     * @throws IOException
     */
    public void outputStream(HttpServletResponse response, InputStream in) throws IOException {
        response.setContentType("image/jpeg");
        OutputStream os = response.getOutputStream();
        byte[] b = new byte[1024];
        while (in.read(b) != -1) {
            os.write(b);
        }
        in.close();
        os.flush();
        os.close();
    }

    @RequestMapping(value = "/editParkDepot", method = RequestMethod.GET)
    @ResponseBody
    public Tip editParkDepot() throws Exception {
        Tip tip = new Tip();
        int a = 0;
        PageInfo<ParkDepot> pi = parkDepotService.list(new HashMap<>());
        for (ParkDepot pd : pi.getList()) {
            tip = HikUtils.getParkingInfoByParkCode(pd.getHikId());
            if (tip.getSuccess()) {
                if (tip.getData() != null) {
                    ParkDepotInfo p = JSONObject.parseObject(JSONArray.toJSONString(tip.getData()), ParkDepotInfo.class);
                    if (p != null) {
                        pd.setName(p.getParkName());
                        pd.setAddress(p.getDescription());
                        pd.setLat(p.getParkLatitude().doubleValue());
                        pd.setLng(p.getParkLongitude().doubleValue());
                        pd.setParkType(p.getParkType());
                        pd.setParkLevel(p.getParkLevel());
                        parkDepotService.updateById(pd);
                        a++;
                    }
                }
            }
        }
        System.out.println("修改了：" + a + "条");

        return new Tip();
    }

    //---------------------------- property -------------------------------

    @Resource
    private ParkDepotService parkDepotService;

    @Resource
    private UserService userService;

    @Resource
    private ReservationRecordService reservationRecordService;

    @Resource
    private PersonalMessageService personalMesssageService;

}
